﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace VectorEditor
{
	public delegate void ContentChangedEventHandler();
    public class Document : ISerializable
	{
		public List<Primitive> Primitives { get; set; }
		public float Width { get; set; }
		public float Height { get; set; }
        public event ContentChangedEventHandler ContentChanged;
		public Document()
		{
			Primitives = new List<Primitive>();
			Width = 500;
			Height = 375;
		}

		public static Document Open(string filename)
		{
			var fs = new FileStream(filename, FileMode.Open);
			try
			{
                var document = new Document();
                document.Load(new BinaryReader(fs));
                return document;
			}
			finally
			{
				fs.Close();
			}
		}

		public void Save(string filename)
		{
			var fs = new FileStream(filename, FileMode.Create);
			try
			{
                Save(new BinaryWriter(fs));
			}
			finally
			{
				fs.Close();
			}
		}

		public void FinishUpdate()
		{
			if (ContentChanged != null)
				ContentChanged.Invoke();
		}


        #region ISerializable Members

        public void Load(BinaryReader reader)
        {
            Width = reader.ReadSingle();
            Height = reader.ReadSingle();
            int primCount = reader.ReadInt32();

            Primitives.Clear();
            Primitives.Capacity = primCount;

            for (int i = 0; i < primCount; i++)
            {
                var typeStr = reader.ReadString();
                var prim = Activator.CreateInstance(Type.GetType(typeStr)) as Primitive;
                prim.Load(reader);
                Primitives.Add(prim);
            }
        }

        public void Save(BinaryWriter writer)
        {
            writer.Write(Width);
            writer.Write(Height);
            writer.Write(Primitives.Count);

            foreach (var prim in Primitives)
            {
                writer.Write(prim.GetType().FullName);
                prim.Save(writer);
            }
        }

        #endregion
    }
}
